#include "hitandrun.h"
#include "Ai.hpp"
#include "math.h"


HitAndRun::HitAndRun(Fruit *idP, int idCible){
    type = T_GUARD;
    idParent = idP;
    age=0;
    x=0;
    y=0;
    value = idCible;
}

bool HitAndRun::execute() {


    if(ai.world.theirFruits.find(value) != ai.world.theirFruits.end())
    {
        signed int difX = idParent->position->X_coord - ai.world.theirFruits[value].position->X_coord, coefX;
        signed int difY = idParent->position->Y_coord - ai.world.theirFruits[value].position->Y_coord, coefY;

        (difX > 0) ? coefX = 1 : coefX = -1;
        (difY > 0) ? coefY = 1 : coefY = -1;

        if(fabs(difX) > idParent->getReach() &&
           fabs(difY) > idParent->getReach())
        {
            path.clear();
            pf.start = idParent->position;
            pf.end = &ai.world.at(ai.world.theirFruits[value].position->X_coord+idParent->getReach() * coefX, ai.world.theirFruits[value].position->Y_coord+idParent->getReach()*coefY);
            if(pf.compute(&path,0,0)==false) return false;
            {
                list<map_chunk*>::iterator it = path.begin();
                for( int i = 0; i < idParent->speed; i++ ) if( it != path.end() )it++;
                if( it == path.end() ) it--;
                if( (*it) == pf.end ) it--;
                if(idParent->move((*it)->X_coord, (*it)->Y_coord ) !=OK) return false;
            }
        }
        else if(idParent->actionsRestantes < 2)
        {
            idParent->attack(value);
        }
        else if(fabs(difX) < idParent->getReach() &&
                fabs(difY) < idParent->getReach())
        {
            path.clear();
            pf.start = idParent->position;
            pf.end = &ai.world.at(ai.world.theirFruits[value].position->X_coord+idParent->getReach() * coefX, ai.world.theirFruits[value].position->Y_coord+idParent->getReach()*coefY);
            if(pf.compute(&path,0,0)==false) return false;
            {
                list<map_chunk*>::iterator it = path.begin();
                for( int i = 0; i < idParent->speed; i++ ) if( it != path.end() )it++;
                if( it == path.end() ) it--;
                if( (*it) == pf.end ) it--;
                if(idParent->move((*it)->X_coord, (*it)->Y_coord ) !=OK) return false;
            }
        }
    }

    return value;
}


